package com.aegean.MonitorExamSYS.examinee.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Hibernate;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.aegean.MonitorExamSYS.examinee.business.ExamineeBusiness;
import com.aegean.MonitorExaxSYS.model.ExamineeValue;
import com.aegean.MonitorExaxSYS.model.component.Photo;
import com.opensymphony.xwork2.ActionSupport;

@Controller("UserRegister")
@Scope("prototype")
public class UserRegisterOne extends ActionSupport {
	@Resource
	ExamineeBusiness business;
	private ExamineeValue user;
	private File photo;
	private String photoFileName;
	private String photoContentType;
	private String userRPwd;

	public String getUserRPwd() {
		return userRPwd;
	}

	public void setUserRPwd(String userRPwd) {
		this.userRPwd = userRPwd;
	}

	public ExamineeValue getUser() {
		return user;
	}

	public void setUser(ExamineeValue user) {
		this.user = user;
	}

	public File getPhoto() {
		return photo;
	}

	public void setPhoto(File photo) {
		this.photo = photo;
	}

	public String getPhotoFileName() {
		return photoFileName;
	}

	public void setPhotoFileName(String photoFileName) {
		this.photoFileName = photoFileName;
	}

	public String getPhotoContentType() {
		return photoContentType;
	}

	public void setPhotoContentType(String photoContentType) {
		this.photoContentType = photoContentType;
	}

	@Override
	public void validate() {
		// TODO Auto-generated method stub
		if (photo == null || photo.length() == 0) {
			this.addFieldError("photo", "对不起，该头像不能为空");
		}
		boolean result = business.validateUser(user.getUser_Login());
		if (result == false) {
			this.addFieldError("user.user_Login", "对不起,该用户名已经注册！");
		}

	}

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		try {
			Photo sphoto = new Photo();
			sphoto.setPhoto(Hibernate.createBlob(new FileInputStream(photo)));
			sphoto.setPhoto_Name(photoFileName);
			sphoto.setPhoto_Type(photoContentType);
			user.setUser_Photo(sphoto);
			user = business.insertUser(user);
			if (user != null && user.getUser_Id() != -1) {
				ServletActionContext.getRequest().getSession()
						.setAttribute("UserRegister", user);
				return SUCCESS;
			} else {
				return ERROR;
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
			return INPUT;
		}
	}

}
